package com.guyaning.deyson_core.core.net;

import com.guyaning.deyson_core.core.app.Config_Type;
import com.guyaning.deyson_core.core.app.Deyson;

import java.util.ArrayList;
import java.util.WeakHashMap;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 * Created by Administrator on 2018/4/10.
 */

public class RestCreator {

    /**
     * 参数容器
     */
    private static final class ParamsHolder{
        public static final WeakHashMap<String,Object> PARAMS = new WeakHashMap<>();
    }

    public static WeakHashMap<String,Object> getParams(){
        return ParamsHolder.PARAMS;
    }

    /**
     * 创建OkHttpClinet
     */
    private static final class OkHttpHolder {

        private static final int TIME_OUT = 60;

        private static final OkHttpClient.Builder BUILDER = new OkHttpClient.Builder();

        private static final ArrayList<Interceptor> INTERCEPTORS = Deyson.getConfiguration(Config_Type.INTERCEPTOR);

        private static OkHttpClient.Builder addInterceptor() {
            if (INTERCEPTORS != null && !INTERCEPTORS.isEmpty()) {
                for (Interceptor interceptor : INTERCEPTORS) {
                    BUILDER.addInterceptor(interceptor);
                }
            }
            return BUILDER;
        }

        private static final OkHttpClient OK_HTTP_CLIENT = addInterceptor()
                .connectTimeout(TIME_OUT, TimeUnit.SECONDS)
                .build();
    }

    /**
     * 创建全局的Retrofit的客户端
     */
    private static final class RetrofitHolder {

        private static final String BASE_URL =  Deyson.getConfiguration(Config_Type.API_HOST);

        private static final Retrofit RETROFIT_CLIENT = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(OkHttpHolder.OK_HTTP_CLIENT)
                .addConverterFactory(ScalarsConverterFactory.create())
                .build();
    }


    private static final class RestSeviceHolder{

        private static final  ResetService RESET_SERVICE =
                RetrofitHolder.RETROFIT_CLIENT.create(ResetService.class);
    }

    public static ResetService getResetService(){
        return RestSeviceHolder.RESET_SERVICE;
    }
}
